package com.wans.easyuibackend.utils.data_assembly;

import com.wans.easyuibackend.exception.data.DataFormatException;
import com.wans.easyuibackend.mapper.StaffMapper;
import com.wans.easyuibackend.param.response.ExcelStaffInfo;
import com.wans.easyuibackend.pojo.StaffInfo;
import com.wans.easyuibackend.utils.validation.DataValidation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Objects;

@Component
@SuppressWarnings({"all"})
public class ExcelStaffAssembly {
    @Autowired
    private DataValidation dataValidation;
    @Autowired
    private StaffMapper staffMapper;


    /**
     * @param staffInfo 文件流
     * @return
     */
    public ArrayList<ExcelStaffInfo> ExcelStaffAssembly(MultipartFile staffInfo) {

        //数据
        ArrayList<ExcelStaffInfo> staffInfos = new ArrayList<>();

        //// 使用ISO 8601日期格式
        DateTimeFormatter isoLocalDate = DateTimeFormatter.ISO_LOCAL_DATE;

        try (InputStream inputStream = staffInfo.getInputStream()) {
            Workbook workbook;
            if (Objects.requireNonNull(staffInfo.getOriginalFilename()).endsWith("xlsx")) {
                //workbook = new XSSFWorkbook(inputStream);
                // 报错
                 workbook = null;
            } else if (staffInfo.getOriginalFilename().endsWith("xls")) {
                workbook = new HSSFWorkbook(inputStream);
            } else {
                throw new RuntimeException("Unsupported file type");
            }

            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    //第一行 行头
                    String rowNameCount = "";

                    for (Cell cell : row) {
                        rowNameCount += cell.toString();
                    }

                    if (!rowNameCount.equals("姓名姓名全拼性别证件类型证件号码出生日期手机号电子邮箱")) {
                        //行头不对
                        throw new RuntimeException("Excel格式不正确");
                    }

                    continue;
                }

                ExcelStaffInfo info = new ExcelStaffInfo();
                info.setRowNum(row.getRowNum());
                for (Cell cell : row) {

                    // 读取单元格数据 注意：这里需要根据单元格的实际类型进行处理
                    switch (cell.getColumnIndex()) {
                        case 0:
                            info.setStaffName(cell.toString());
                            break;
                        case 1:
                            info.setStaffNameSpelling(String.valueOf(cell));
                            break;
                        case 2:
                            info.setStaffGender(Integer.parseInt(cell.toString()));
                            break;
                        case 3:
                            info.setStaffIdentityType(Integer.parseInt(cell.toString()));
                            break;
                        case 4:
                            info.setStaffIdentity(cell.toString());
                            break;
                        case 5:
                            info.setStaffBirthday(LocalDate.parse(cell.toString(), isoLocalDate));
                            break;
                        case 6:
                            info.setStaffPhoneNumber(cell.toString());
                            break;
                        case 7:
                            info.setStaffEmail(cell.toString());
                            break;
                        default:
                            throw new RuntimeException("Excel格式不正确");  //多行
                    }
                }
                staffInfos.add(info);
            }

            workbook.close();
            return staffInfos;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to process Excel file");
        }
    }


    /**
     * @param staffInfos 人员信息
     * @return
     */
    public ArrayList<String> ImprotStaffInfo(ArrayList<ExcelStaffInfo> staffInfos) {
        //错误信息
        ArrayList<String> errorMsg = new ArrayList<>();

        for (ExcelStaffInfo staffInfo : staffInfos) {
            try {
                StaffInfo info = new StaffInfo(staffInfo.getStaffId(), staffInfo.getStaffName(), staffInfo.getStaffNameSpelling(), staffInfo.getStaffGender(), staffInfo.getStaffIdentityType(), staffInfo.getStaffIdentity(), staffInfo.getStaffBirthday(), staffInfo.getStaffPhoneNumber(), staffInfo.getStaffEmail(), staffInfo.getCreateTime(), staffInfo.getUpdateTime());
                boolean staffValidation = dataValidation.staffValidation(info);
                if (!staffValidation) {
                    throw new DataFormatException("400","数据格式异常");
                }
            } catch (StringIndexOutOfBoundsException e) {
                errorMsg.add("第" + (staffInfo.getRowNum() + 1) + "行 出现错误：身份证号错误");
            } catch (Exception e) {
                errorMsg.add("第" + (staffInfo.getRowNum() + 1) + "行 出现错误：" + e.getMessage());
            }
        }

        //如果全部无错就导入数据
        if (errorMsg.isEmpty()) {
            //没有数据错误
            for (ExcelStaffInfo staffInfo : staffInfos) {
                StaffInfo info = new StaffInfo(staffInfo.getStaffId(), staffInfo.getStaffName(), staffInfo.getStaffNameSpelling(), staffInfo.getStaffGender(), staffInfo.getStaffIdentityType(), staffInfo.getStaffIdentity(), staffInfo.getStaffBirthday(), staffInfo.getStaffPhoneNumber(), staffInfo.getStaffEmail(), staffInfo.getCreateTime(), staffInfo.getUpdateTime());
                staffMapper.addStaffInfo(info);
            }
        }


        return errorMsg;
    }

}
